package cn.exrick.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.exrick.common.alipay.AlipayService;
import cn.exrick.pojo.TbOrderReturnExchange;
import cn.exrick.service.OrderReturnExchangeService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.exrick.common.exception.NeedLoginException;
import cn.exrick.common.exception.XmallException;
import cn.exrick.common.jedis.JedisClient;
import cn.exrick.pojo.TbExpress;
import cn.exrick.pojo.common.Result;
import cn.exrick.pojo.dto.CreateOrderRequest;
import cn.exrick.pojo.dto.ItemDto;
import cn.exrick.pojo.dto.OrderDetail;
import cn.exrick.pojo.front.CartProduct;
import cn.exrick.pojo.front.Member;
import cn.exrick.pojo.front.Order;
import cn.exrick.service.CartService;
import cn.exrick.service.ExpressService;
import cn.exrick.service.ItemService;
import cn.exrick.service.LoginService;
import cn.exrick.service.OrderFrontService;
import cn.exrick.service.OrderService;
import cn.exrick.utils.ControllerUtils;
import cn.exrick.utils.EmailUtil;
import cn.exrick.utils.IPInfoUtil;
import cn.exrick.utils.KdniaoTrackQueryAPI;
import cn.exrick.utils.ResultUtil;
import cn.exrick.utils.enums.ExpressTypeEnum;
import cn.exrick.utils.mybatis.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Exrickx
 */
@RestController
@Api(description = "订单")
public class OrderFrontController {

	private final static Logger log = LoggerFactory.getLogger(OrderFrontController.class);

	@Autowired
	private JedisClient jedisClient;

	@Autowired
	private OrderFrontService orderService;

	@Autowired
	private OrderService orderServ;

	@Autowired
	private LoginService loginService;

	@Autowired
	EmailUtil emailUtil;

	@Autowired
	CartService cartService;

	@Autowired
	private ExpressService expressService;

	@Autowired
	private ItemService itemService;

	@Autowired
	private KdniaoTrackQueryAPI api;

	@Autowired
	private AlipayService alipayService;

	@Autowired
	private OrderReturnExchangeService returnExchangeService;

	private static final String CLOSE_PRE = "XMALL_CLOSE_PRE";

	@RequestMapping(value = "/member/orderList", method = RequestMethod.GET)
	@ApiOperation(value = "获得用户所有订单")
	public Result<Page<Order>> getOrderList(String token, @RequestParam(defaultValue = "0") int page,
			@RequestParam(defaultValue = "5") int size, Integer status) {
		page++;
		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}
		Page<Order> pageOrder = orderService.getOrderList(member.getId(), page, size, status);
		return new ResultUtil<Page<Order>>().setData(pageOrder);
	}

	@RequestMapping(value = "/member/orderDetail", method = RequestMethod.GET)
	@ApiOperation(value = "通过id获取订单")
	public Result<Order> getOrder(String token, String orderId) {
		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}
		Order order = orderService.getOrder(Long.valueOf(orderId));
		if (!order.getMemberId().equals(member.getId())) {
			throw new XmallException("你不能查看他人的订单信息");
		}
		return new ResultUtil<Order>().setData(order);
	}

	@RequestMapping(value = "/member/addOrder", method = RequestMethod.POST)
	@ApiOperation(value = "创建订单")
	public Result<Object> addOrder(String token, Long addressId, String itemIds, String buyerMessage,
			String expressType) {
		// 防炸库验证
		String ip = IPInfoUtil.getIpAddr(ControllerUtils.getRequest());
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
			ip = "127.0.0.1";
		}
		String redisKey = "addOrder_" + ip;
		String temp = jedisClient.get(redisKey);
		if (StringUtils.isNotBlank(temp)) {
			throw new XmallException("您提交的太频繁啦");
		}

		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}

		if (!ExpressTypeEnum.validate(expressType)) {
			throw new XmallException("请选择物流方式");
		}

		String[] itemIdss = itemIds.split(",");
		List<CartProduct> list = new ArrayList<>();
		for (String itemId : itemIdss) {
			CartProduct cartProduct = cartService.getCart(member.getId(), Long.parseLong(itemId));
			if (cartProduct == null) {
				throw new XmallException("提交的商品信息有误");
			}
			list.add(cartProduct);
		}
		CreateOrderRequest request = new CreateOrderRequest();
		request.setAddressId(addressId);
		request.setBuyerMessage(buyerMessage);
		request.setCartProductList(list);
		request.setExpressType(expressType);
		request.setMemberId(member.getId());
		Long orderId = orderService.createOrder(request);

		// 记录缓存
		jedisClient.set(redisKey, "ADDED");
		jedisClient.expire(redisKey, 10);
		return new ResultUtil<Object>().setData(orderId.toString());
	}

	@RequestMapping(value = "/member/buyNow", method = RequestMethod.POST)
	@ApiOperation(value = "立即购买")
	public Result<Object> buyNow(String token, Long addressId, Long itemId, @RequestParam(defaultValue = "1") int num,
			String buyerMessage, String expressType) {
		// 防炸库验证
		String ip = IPInfoUtil.getIpAddr(ControllerUtils.getRequest());
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
			ip = "127.0.0.1";
		}
		String redisKey = "addOrder_" + ip;
		String temp = jedisClient.get(redisKey);
		if (StringUtils.isNotBlank(temp)) {
			throw new XmallException("您提交的太频繁啦");
		}

		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}

		if (!ExpressTypeEnum.validate(expressType)) {
			throw new XmallException("请选择物流方式");
		}

		ItemDto itemDto = itemService.getItemById(itemId);
		if (itemDto == null) {
			throw new XmallException("商品不存在");
		}

		List<CartProduct> list = new ArrayList<>();
		CartProduct cartProduct = cartService.getCart(member.getId(), itemId);
		if (cartProduct == null) {
			cartService.addCart(member.getId(), itemId, num);
			cartProduct = cartService.getCart(member.getId(), itemId);
		}
		list.add(cartProduct);

		CreateOrderRequest request = new CreateOrderRequest();
		request.setAddressId(addressId);
		request.setBuyerMessage(buyerMessage);
		request.setCartProductList(list);
		request.setExpressType(expressType);
		request.setMemberId(member.getId());
		Long orderId = orderService.createOrder(request);

		// 记录缓存
		jedisClient.set(redisKey, "ADDED");
		jedisClient.expire(redisKey, 10);
		return new ResultUtil<Object>().setData(orderId.toString());
	}

	@RequestMapping(value = "/member/cancelOrder", method = RequestMethod.POST)
	@ApiOperation(value = "取消订单")
	public Result<Object> cancelOrder(String token, Long orderId) {
		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}
		Order order = orderService.getOrder(orderId);
		if (order == null) {
			throw new XmallException("通过id获取订单失败");
		}
		if (!order.getMemberId().equals(member.getId())) {
			throw new XmallException("你不能操作其他用户的订单");
		}
		int result = orderService.cancelOrder(orderId);
		return new ResultUtil<Object>().setData(result);
	}

	@RequestMapping(value = "/member/delOrder", method = RequestMethod.GET)
	@ApiOperation(value = "删除订单")
	public Result<Object> delOrder(String token, Long orderId) {
		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}
		Order order = orderService.getOrder(orderId);
		if (order == null) {
			throw new XmallException("通过id获取订单失败");
		}
		if (!order.getMemberId().equals(member.getId())) {
			throw new XmallException("你不能操作其他用户的订单");
		}
		int result = orderService.delOrder(orderId);
		return new ResultUtil<Object>().setData(result);
	}

	@RequestMapping(value = "/member/payOrder", method = RequestMethod.GET)
	@ApiOperation(value = "支付订单")
	public Result<Object> payOrder(String token, Long orderId) {
		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}
		Order order = orderService.getOrder(orderId);
		if (order == null) {
			throw new XmallException("通过id获取订单失败");
		}
		if (!order.getMemberId().equals(member.getId())) {
			throw new XmallException("你不能操作其他用户的订单");
		}
		// 判断订单状态

		String packageParams = "type=order";
		String result = alipayService.sendAppPay(String.valueOf(order.getOrderId()), "商品描述", "商品标题", packageParams,
				order.getOrderTotal());

		/*
		 * String v = jedisClient.get(CLOSE_PRE); if (StrUtil.isNotBlank(v)) { return
		 * new ResultUtil<Object>().setErrorMsg("这么晚啦别支付啦，请于每日7:00am起支付"); } //防炸库验证
		 * String ip = IPInfoUtil.getIpAddr(request); if ("0:0:0:0:0:0:0:1".equals(ip))
		 * { ip = "127.0.0.1"; } String redisKey = "payOrder_" + ip; String temp =
		 * jedisClient.get(redisKey); if (StringUtils.isNotBlank(temp)) { throw new
		 * XmallException("您提交的太频繁啦"); }
		 * 
		 * String result = orderService.payOrder(tbThanks);
		 */

		// 记录缓存
		/*
		 * jedisClient.set(redisKey, "ADDED"); jedisClient.expire(redisKey, 120);
		 */
		return new ResultUtil<Object>().setData(result);
	}

	@RequestMapping(value = "/member/orderExpress", method = RequestMethod.POST)
	@ApiOperation(value = "查询订单物流信息")
	public Result<String> getExpress(String token, Long orderId) throws Exception {
		// 防炸库验证
		String ip = IPInfoUtil.getIpAddr(ControllerUtils.getRequest());
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
			ip = "127.0.0.1";
		}
		String redisKey = "orderExpress_" + ip;
		String temp = jedisClient.get(redisKey);
		if (StringUtils.isNotBlank(temp)) {
			throw new XmallException("您提交的太频繁啦");
		}
		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}
		Order order = orderService.getOrder(orderId);
		if (order == null) {
			throw new XmallException("通过id获取订单失败");
		}
		if (!order.getMemberId().equals(member.getId())) {
			throw new XmallException("你不能操作其他用户的订单");
		}
		if (order.getOrderStatus() < Order.ORDER_STATUS_WAIT_RECE) {
			throw new XmallException("订单未发货");
		}
		if (order.getOrderStatus() == Order.ORDER_STATUS_CLOSE) {
			throw new XmallException("订单已关闭");
		}

		if (StringUtils.isEmpty(order.getShippingName())) {
			throw new XmallException("未知快递");
		}
		TbExpress express = expressService.findByName(order.getShippingName());
		if (express == null) {
			throw new XmallException("未知快递");
		}
		try {
			String result = api.getOrderTracesByJson(express.getExpressCode(), order.getShippingCode());
			return new ResultUtil<String>().setData(result);
		} catch (Exception e) {
			throw new XmallException("查询出错");
		}
	}

	@RequestMapping(value = "/member/receiveOrder", method = RequestMethod.POST)
	@ApiOperation(value = "用户收货")
	public Result<Object> receiveOrder(String token, Long orderId) throws Exception {
		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}
		OrderDetail order = orderServ.getOrderDetail(String.valueOf(orderId));
		if (order == null) {
			throw new XmallException("通过id获取订单失败");
		}
		if (!order.getTbOrder().getUserId().equals(member.getId())) {
			throw new XmallException("你不能操作其他用户的订单");
		}
		if (order.getTbOrder().getStatus() != Order.ORDER_STATUS_WAIT_RECE) {
			throw new XmallException("当前订单状态不能确认收货");
		}
		order.getTbOrder().setStatus(Order.ORDER_STATUS_WAIT_RATE);
		orderServ.update(order.getTbOrder());
		return new ResultUtil<Object>().setData(null);
	}

	@RequestMapping(value = "/member/addOrderReturnExchange", method = RequestMethod.POST)
	@ApiOperation(value = "申请订单售后")
	public Result<Object> addOrderReturnExchange(String token, String orderId, Integer type, String alipayAccount,
												 String reason, String image) {
		// 防炸库验证
		String ip = IPInfoUtil.getIpAddr(ControllerUtils.getRequest());
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
			ip = "127.0.0.1";
		}
		String redisKey = "addOrderReturnExchange_" + ip;
		String temp = jedisClient.get(redisKey);
		if(StringUtils.isNotBlank(temp)) {
			throw new XmallException("您提交的太频繁啦");
		}
		Member member = loginService.getUserByToken(token);
		if(member == null) {
			throw new NeedLoginException();
		}
		if(type == null) {
			throw new XmallException("请选择售后类型");
		}
		OrderDetail order = orderServ.getOrderDetail(String.valueOf(orderId));
		if (order == null) {
			throw new XmallException("通过id获取订单失败");
		}
		if (!order.getTbOrder().getUserId().equals(member.getId())) {
			throw new XmallException("你不能操作其他用户的订单");
		}
		// 已支付 - 交易完成 之间的状态才可以申请售后
		if (order.getTbOrder().getStatus() < 1
				|| order.getTbOrder().getStatus() > 5) {
			throw new XmallException("当前订单状态不能申请售后");
		}

		TbOrderReturnExchange returnExchange = returnExchangeService.getByOrderId(orderId);

		if(null != returnExchange && returnExchange.getStatus() == 0){
			throw new XmallException("当前订单已申请售后,正在审核中");
		}

		returnExchange = new TbOrderReturnExchange();
		returnExchange.setMemberId(member.getId());
		returnExchange.setOrderId(orderId);
		returnExchange.setType(type);
		returnExchange.setStatus(0);
		returnExchange.setReason(reason);
		returnExchange.setAlipayAccount(alipayAccount);
		returnExchange.setImage(image);
		returnExchange.setCreated(new Date());
		returnExchange.setUpdated(new Date());

		Integer id = returnExchangeService.save(returnExchange);

		// 记录缓存
		jedisClient.set(redisKey, "ADDORE");
		jedisClient.expire(redisKey, 10);

		return new ResultUtil<Object>().setData(null);
	}

	@RequestMapping(value = "/member/orderReturnExchangeDetail", method = RequestMethod.GET)
	@ApiOperation(value = "获取订单售后详情")
	public Result<Object> orderReturnExchange(String token, String orderId) {
		Member member = loginService.getUserByToken(token);
		if(member == null) {
			throw new NeedLoginException();
		}
		OrderDetail order = orderServ.getOrderDetail(String.valueOf(orderId));
		if (order == null) {
			throw new XmallException("通过id获取订单失败");
		}
		if (!order.getTbOrder().getUserId().equals(member.getId())) {
			throw new XmallException("你不能操作其他用户的订单");
		}

		TbOrderReturnExchange returnExchange = returnExchangeService.getByOrderId(orderId);

		if(null == returnExchange){
			throw new XmallException("当前订单还未提交售后申请");
		}

		return new ResultUtil<Object>().setData(returnExchange);
	}

}
